package cn.jbolt.core.handler.base;

import cn.jbolt.core.base.config.JBoltConfig;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;

import javax.servlet.http.HttpServletRequest;
/**
 * 从二级域名解析tenantSn
 * @ClassName:  JBoltSaasTenantIdDomainParser
 * @author: JFinal学院-小木 QQ：909854136
 * @date:   2022年2月20日
 */
public class JBoltSaasTenantSnDomainParser implements JBoltSaasTenantSnParser {
	private boolean isFail;
	@Override
	public String parse(Invocation inv) {
		return parse(inv.getController());
	}

	@Override
	public String parse(Controller ctrl) {
		return parse(ctrl.getRequest());
	}

	@Override
	public String parse(HttpServletRequest request) {
		//获取域名
	    String serverName = request.getServerName();
	   //如果访问的全域名 不管总部还是租户
	    if(serverName.equalsIgnoreCase(JBoltConfig.DOMAIN)||serverName.equalsIgnoreCase(JBoltConfig.SAAS_TENANT_DOMAIN)) {
	    	isFail = false;
		   return null;
	    }
	   //获取主域名
	    String domain = serverName.substring(serverName.indexOf(".")+1);
	    if(StrKit.isBlank(domain)) {
	    	isFail = false;
	    	return null;
		}

	    //如果不是二级域名 就返回
	    if(!domain.equalsIgnoreCase(JBoltConfig.SAAS_TENANT_DOMAIN)) {
	    	isFail = false;
	       return null;
	    }

	    //获取租户sn
	    String tenantSn = serverName.substring(0, serverName.indexOf("."));
	    //如果获取为空就忽略
	    if(StrKit.isBlank(tenantSn)){
	    	isFail = true;
	    	return null;
	    }

		return tenantSn;
	}

	@Override
	public boolean isFail() {
		return isFail;
	}

}
